﻿using System;
using System.Collections.Generic;
using System.Web;
using System.IO;


namespace CCPSIP.Sticker
{
    /// <summary>CCPSIP_024：取得個人貼圖的檔案列表 API</summary>
    /// idHeader = 裝置 UUID 前八碼。iOS 請使用 [CCPCrypto getIdHeader] 呼叫。
    /// checkcode = 裝置限時驗證碼。iOS 請使用 [CCPCrypto getCheckcode] 呼叫。

    public class sticker_list : IHttpHandler
    {
        private const string kStickerDirDefault = @"\\192.168.19.1\Sticker_Default\Default";
        private const string kStickerRootDir = @"\\192.168.19.1\iSender_D";
        private const string kWinUserId = "ccpsip_cloud";
        private static byte[] kWinUserKey = { 0x59, 0x4C, 0x43, 0x71, 0x6A,
                                          0x6D, 0x44, 0x6A, 0x32, 0x5A,
                                          0x72, 0x62, 0x72, 0x43, 0x39,
                                          0x68, 0x51, 0x6E, 0x63, 0x6B,
                                          0x57, 0x32, 0x64, 0x74, 0x62
                                        };


        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";

            try
            {
                //【01】取得POST參數，驗證身分
                //
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];

                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (userInfo == null)
                {
                    throw new Exception("Error_01: Cannot identify this device");//無法識別此裝置
                }


                //【02】組合資料夾路徑
                //
                string userDirName = userInfo.SIP_Num;
                if (SipKit.isHQMobileExt(userInfo.SIP_Num))
                {
                    userDirName = SipKit.getHQDesktopExt(userInfo.SIP_Num);
                }
                string stickerDir = string.Format(@"{0}\{1}\Stickers", kStickerRootDir, userDirName);


                //【03】切換網域身分存取資料夾
                //
                List<EasyDirInfo> dirList = new List<EasyDirInfo>();

                string tempCode = System.Text.Encoding.UTF8.GetString(kWinUserKey);

                using (new Tools.Impersonator(kWinUserId, "", tempCode))
                {
                    //【04】預設貼圖資料夾
                    //
                    if (Directory.Exists(kStickerDirDefault))
                    {
                        List<EasyDirInfo> dirList1 = new List<EasyDirInfo>();
                        DirectoryInfo dInfo = new DirectoryInfo(kStickerDirDefault);
                        foreach (DirectoryInfo subDir in dInfo.GetDirectories())
                        {
                            EasyDirInfo eDirInfo = new EasyDirInfo(subDir, "*.png", true);
                            if (eDirInfo.FileList.Count > 0)
                                dirList1.Add(eDirInfo);
                        }
                        dirList1.Sort();
                        dirList.AddRange(dirList1);
                    }


                    //【05】個人貼圖資料夾
                    //
                    if (Directory.Exists(stickerDir))
                    {
                        List<EasyDirInfo> dirList2 = new List<EasyDirInfo>();
                        DirectoryInfo dInfo = new DirectoryInfo(stickerDir);
                        foreach (DirectoryInfo subDir in dInfo.GetDirectories())
                        {
                            EasyDirInfo eDirInfo = new EasyDirInfo(subDir, "*.png", false);
                            if (eDirInfo.FileList.Count > 0)
                                dirList2.Add(eDirInfo);
                        }
                        dirList2.Sort();
                        dirList.AddRange(dirList2);
                    }
                }//End of Impersonator


                //【99】回傳結果
                //
                resp.ContentType = "application/json";
                resp.Charset = null;
                fastJSON.JSON.Instance.Parameters.EnableAnonymousTypes = true;
                resultStr = fastJSON.JSON.Instance.ToJSON(dirList.ToArray());
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }



        #region 資料夾檔案簡易資訊

        [Serializable()]
        private class EasyDirInfo : IComparable
        {
            private string _Name;
            private string _IsDefault;
            private List<EasyFileInfo> _FileList;

            public string Name { get { return this._Name; } }
            public string IsDefault { get { return this._IsDefault; } }
            public List<EasyFileInfo> FileList { get { return this._FileList; } }

            public EasyDirInfo(DirectoryInfo dInfo, string searchPattern, bool isDefault)
            {
                _Name = dInfo.Name;
                _IsDefault = (isDefault ? "Y" : "N");
                _FileList = new List<EasyFileInfo>();
                foreach (FileInfo fInfo in dInfo.GetFiles(searchPattern))
                {
                    EasyFileInfo eFileInfo = new EasyFileInfo(fInfo);
                    _FileList.Add(eFileInfo);
                }
                _FileList.Sort();
            }

            public int CompareTo(object obj)
            {
                if (obj is EasyDirInfo)
                {
                    EasyDirInfo dInfo = (EasyDirInfo)obj;
                    return this.CompareTo(dInfo);
                }
                else
                {
                    throw new Exception("ERROR_CANNOT_COMPARE");
                }
            }

            public int CompareTo(EasyDirInfo dInfo)
            {
                return _Name.CompareTo(dInfo._Name);
            }
        }


        [Serializable()]
        private class EasyFileInfo : IComparable
        {
            private string _Name;
            private long _Length;
            private DateTime _LastWriteTime;

            public string Name { get { return this._Name; } }
            public long Length { get { return this._Length; } }
            public DateTime LastWriteTime { get { return this._LastWriteTime; } }

            public EasyFileInfo(FileInfo fInfo)
            {
                _Name = fInfo.Name;
                _Length = fInfo.Length;
                _LastWriteTime = fInfo.LastWriteTime;
            }

            public int CompareTo(object obj)
            {
                if (obj is EasyFileInfo)
                {
                    EasyFileInfo fInfo = (EasyFileInfo)obj;
                    return this.CompareTo(fInfo);
                }
                else
                {
                    throw new Exception("ERROR_CANNOT_COMPARE");
                }
            }

            public int CompareTo(EasyFileInfo fInfo)
            {
                return _Name.CompareTo(fInfo._Name);
            }
        }

        #endregion

    }
}
